import sqlglot
from sqlglot import exp

def normalize_sql(sql):
    """标准化SQL语句：移除不影响逻辑的差异"""
    try:
        # 解析为AST
        ast = sqlglot.parse_one(sql)
        
        # 标准化处理
        normalized = ast.transform(remove_aliases).transform(anonymize_values)
        
        # 统一排序（对某些子句排序不敏感的SQL）
        if isinstance(normalized, exp.Select):
            normalized = normalize_select_order(normalized)
            
        return normalized
    except Exception as e:
        print(f"解析SQL失败: {e}")
        return None

def remove_aliases(node):
    """移除表/列别名"""
    if isinstance(node, (exp.Alias, exp.TableAlias)):
        return node.this
    return node

def anonymize_values(node):
    """匿名化值（数字、字符串等）"""
    if isinstance(node, exp.Literal):
        if node.is_string:
            return exp.Literal.string("S")
        elif node.is_number:
            return exp.Literal.number("N")
    return node

def normalize_select_order(select):
    """统一SELECT语句中子句的顺序"""
    clauses_order = [
        'with', 'distinct', 'expressions', 'from', 'joins',
        'where', 'group', 'having', 'order', 'limit', 'offset'
    ]
    
    normalized = select.copy()
    
    # 确保子句按标准顺序排列
    for clause in clauses_order:
        if select.args.get(clause):
            normalized.set(clause, select.args[clause])
    
    return normalized